<template>
  <view>
    <view class="goods-banner">
      <swiper
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        circular
        indicator-color="#FFFFFF70"
        indicator-active-color="#fff"
        class="goods-banner-swiper"
      >
        <swiper-item v-for="(item, index) in goodsBanner" :key="index">
          <view class="banner-swiper-item">
            <image
              :src="item"
              mode="scaleToFill"
              @click="TanPreviewImage(index, 'goodsBanner')"
              webp
              class="banner-item-img am-block"
            ></image>
          </view>
        </swiper-item>
      </swiper>
    </view>
    <view class="goods-info">
      <view
        style="align-items: flex-end"
        class="goods-price-wrap am-flex-rc-between"
      >
        <view class="goods-price-box">
          ￥
          <text class="goods-price-num">{{
            goodsData.skuChildList[0].purchasePrice
          }}</text>
          <text
            v-if="goodsData.skuChildList[0].originalPrice"
            style="
              font-weight: 400;
              font-size: 30rpx;
              color: #c5c6c8;
              text-decoration: line-through;
            "
          >
            ￥
            <text>{{ goodsData.skuChildList[0].originalPrice }}</text>
          </text>
        </view>
        <!-- <view class="brand am-flex-row-center">
          <view class="brand-label">零售价</view>
          <view class="brand-val"
            >¥{{ goodsData.skuChildList[0].purchasePrice || 0 }}</view
          >
        </view> -->
        <div
          style="width: 120rpx; text-align: right"
          class="am-flex-row-center subEntry"
        >
          销量{{ goodsData.salesVolume || 0 }}单
        </div>
      </view>
      <view style="display: flex; justify-content: space-between">
        <text
          v-if="goodsData.name"
          class="am-block am-text-break goods-info-title"
          >{{ goodsData.name }}</text
        >
      </view>
      <!-- <text class="am-block am-text-break goods-info-des">{{ goodsData.memo }}</text> -->
    </view>
    <!-- <view class="goods-info">
      <view class="goods-info-des am-flex-rc-between clear-mt">
        <text>运费服务</text>
        <text @click="showFreight">点击查看详情>></text>
      </view>
    </view> -->
    <view class="goods-info">
      <text class="am-block am-text-break goods-info-title">图文详情</text>
      <text class="am-block am-text-break goods-info-title-second"
        >商品参数</text
      >
      <view class="am-block am-text-break goods-info-des flex">
        <text class="label">分类</text>
        <text class="item"
          >{{ goodsData.firstCategoryName }}-{{ goodsData.categoryName }}</text
        >
      </view>
      <view class="am-block am-text-break goods-info-des flex">
        <text class="label">规格</text>
        <view class="flex-wrap">
          <text
            v-for="(item, ind) in goodsData.skuChildList"
            :key="ind"
            class="specStyle"
            >{{ item.spec }}</text
          >
        </view>
      </view>
      <view class="am-block am-text-break goods-info-des flex">
        <text class="label">库存</text>
        <text class="item">{{ goodsData.stockTotal }}</text>
      </view>
      <!-- <view class="am-block am-text-break goods-info-des flex">
        <text class="label">产品介绍</text>
        <text class="item">{{ goodsData.memo }}</text>
      </view> -->
    </view>
    <view class="goods-picture-wrap">
      <text class="am-block am-text-break goods-info-title-pd">产品介绍</text>
      <text class="am-block am-text-break">{{ goodsData.memo }}</text>

      <image
        :src="item"
        @click="TanPreviewImage(index, 'detailPicture')"
        mode="widthFix"
        v-for="(item, index) in detailPicture"
        :key="item"
        class="am-block goods-picture-list"
        webp
      ></image>
    </view>
    <view v-if="goodsData.video" class="goods-picture-wrap">
      <text class="am-block am-text-break goods-info-title-pd">产品视频</text>
      <video
        :src="goodsData.video"
        class="am-block goods-picture-list"
        webp
      ></video>
    </view>
    <!-- 返回按钮 -->
    <view
      class="short-nav-bar am-flex-rc-center"
      v-if="backBtnShow"
      :style="{ height: `${navigationHeight}px`, top: `${statusBarHeight}px` }"
      @click="pageBack"
    >
      <view
        class="page-back-btn am-flex-rc-center"
        :style="{ height: `${navigationHeight}px` }"
        ><u-icon name="arrow-left" size="40rpx" color="#fff"></u-icon
      ></view>
    </view>
    <view class="footer-bar">
      <view></view>
      <view class="footer-bar-wrap">
        <button
          class="u-reset-button join-cart-btn s-plain-btn footer-bar-button"
          @click="addCart(1)"
          plain
          :class="{ disabled: goodsData.stock === 0 }"
        >
          加入购物车
        </button>
        <button
          class="u-reset-button s-primary-btn footer-bar-button"
          @click="addCart(2)"
          plain
          :class="{ disabled: goodsData.stock === 0 }"
        >
          立即购买
        </button>
      </view>
    </view>
    <view class="footer-bar-place"></view>
    <purchaseGoods
      :showModal="showPay"
      :detail="goodsData"
      @close="onclose"
      @submit="submit"
      :type="type"
    >
    </purchaseGoods>
    <view>
      <u-popup
        v-model="freightShow"
        mode="bottom"
        height="60%"
        border-radius="20"
        :closeable="true"
      >
        <!-- <view class="popup-wrap"> -->
        <view class="popup-block">
          <view class="popup-block__title">
            <view class="fs-20 mb-20">运费说明</view>
            <view class="c-gray"
              >以下是地区运费说明，具体运费可在提交订单时查看</view
            >
          </view>
          <view class="popup-block__item">
            <view class="popup-block__item-title">包邮</view>
            <text class="c-gray">{{ shippingProvince.join('，') }}</text>
          </view>
          <view class="popup-block__item">
            <view class="popup-block__item-title">买家付邮</view>
            <text class="c-gray">{{ postProvince.join('，') }}</text>
            <view
              class="freight-info-block"
              v-for="item in freightSettingsPosts"
              :key="item.id"
            >
              <view class="freight-info-block__left"
                >{{ item.province.city }}：</view
              >
              <view class="freight-info-block__right">
                <text>
                  {{ item.piece }}
                  <text>{{
                    freightParams.billingMethod === 1 ? '件内' : '千克内'
                  }}</text>
                  {{ item.element }}
                  <text>元，</text>
                </text>
                <text>
                  <text>每增加</text>
                  {{ item.increasePiece }}
                  <text
                    >{{
                      freightParams.billingMethod === 1 ? '件' : '千克'
                    }}，增加运费</text
                  >
                  {{ item.increaseElement }}
                  <text class="mr-10">元</text>
                  <text v-if="item.freeCondition === 0"
                    >指定条件包邮：满{{ item.fullPiece
                    }}{{ item.fullPieceType === 0 ? '件' : '元' }}包邮</text
                  >
                </text>
              </view>
            </view>
          </view>
          <view class="popup-block__item">
            <view class="popup-block__item-title">不配送</view>
            <text class="c-gray">{{ noDeliveryProvince.join('，') }}</text>
          </view>
        </view>
        <!-- <view class="close" @click="freightShow = false">关闭</view> -->
        <!-- </view> -->
      </u-popup>
    </view>
  </view>
</template>

<script>
import cloneDeep from 'lodash-es/cloneDeep'
import { apiGoodsDetails } from '@/api/goods.js'
import { appOnLaunch } from '@/utils/appGlobalLifeCycle'
import { apiAddCart } from '@/api/shoppingCart'
import { statusBarHeight, navigationHeight } from '@/utils/systemInfo.js'
import { UPDATE_SHOPPING_CART } from '@/types/globalEventName'
import purchaseGoods from '../../components/purchase-goods/purchase-goods'
import { levelToPriceField } from '@/types/goods.js'
export default {
  data() {
    let pages = getCurrentPages()
    return {
      freightShow: false,
      pageQuery: {},
      goodsData: {
        detailPicture: ''
      },
      fixedBtnTop: statusBarHeight,
      navigationHeight,
      statusBarHeight,
      backBtnShow: pages.length > 1,
      showPay: false,
      type: 1,
      shippingProvince: [],
      postProvince: [],
      noDeliveryProvince: [],
      freightSettingsPosts: []
    }
  },
  components: {
    purchaseGoods
  },
  computed: {
    goodsBanner() {
      if (this.goodsData.banner) {
        let imgList = this.goodsData.banner.split(',')
        return imgList.map((p1) => {
          return p1
        })
      } else {
        return []
      }
    },
    detailPicture() {
      if (this.goodsData.detailPicture) {
        let imgList = this.goodsData.detailPicture.split(',')
        return imgList.map((p1) => {
          return `${p1}?x-oss-process=image/resize,m_lfit,w_750,limit_0/format,webp`
        })
      } else {
        return []
      }
    },
    getDetailsSuccess() {
      return !!this.goodsData.id
    },
    curSupplierLevel() {
      return this.$store.getters.curSupplierLevel
    }
  },
  /**
   * @param {Objcet} options - 页面参数
   * @param {String} options.id - 商品id
   * */
  onLoad(options) {
    this.pageQuery = options
    if (options.id) {
      this.getGoodsDetails()
    }
  },
  onShow() {
    if (!this.$store.getters.isLogin) {
      appOnLaunch()
      return
    }
  },
  onShareAppMessage(res) {
    return {
      title: this.goodsData.name,
      path: '/pages/index/index'
    }
  },
  methods: {
    // 点击运费详情
    // showFreight() {
    //   if (this.goodsData.freightSettings) {
    //     console.log(cloneDeep(this.goodsData))
    //     // 组织运费信息
    //     let {
    //       freightSettingsPosts,
    //       shippingProvince,
    //       postProvince,
    //       noDeliveryProvince
    //     } = cloneDeep(this.goodsData.freightSettings)
    //     let shippingProvinces = this.valJsonParse(shippingProvince)
    //     let postProvinces = this.valJsonParse(postProvince)
    //     let noDeliveryProvinces = this.valJsonParse(noDeliveryProvince)
    //     this.shippingProvince = shippingProvinces.map((item) => item.city)
    //     this.postProvince = postProvinces.map((item) => item.city)
    //     this.noDeliveryProvince = noDeliveryProvinces.map((item) => item.city)
    //     freightSettingsPosts.forEach((item) => {
    //       item.province = this.valJsonParse(item.province)
    //     })
    //     this.freightSettingsPosts = freightSettingsPosts
    //     this.freightShow = true
    //   } else {
    //     this.$am_toast('请先绑定运费模板')
    //   }
    // },
    TanPreviewImage(ind, arr) {
      uni.previewImage({
        current: ind,
        urls: this[arr]
      })
    },
    onclose(show) {
      this.showPay = show
      uni.showTabBar()
    },
    submit(data) {
      uni.showTabBar()
      if (this.type == 1) {
        this.apiAddCart(data)
      } else {
        this.$u.route('pages/place-order/submit-order', {
          val: JSON.stringify(data.val)
        })
      }
      this.showPay = false
    },
    // 启用规格窗口
    addCart(type) {
      this.showPay = true
      uni.hideTabBar()
      this.type = type
    },
    // 递归parase
    valJsonParse(obj) {
      if (typeof obj === 'object') {
        return obj
      } else if (obj === '') {
        return []
      } else {
        return this.valJsonParse(JSON.parse(obj))
      }
    },
    getGoodsDetails() {
      uni.showLoading({
        mask: true
      })
      apiGoodsDetails({
        id: this.pageQuery.id
      })
        .then((res) => {
          let { state, data, msg } = res.data
          if (state === 'OK') {
            this.goodsData = data
            uni.hideLoading()
          } else {
            uni.hideLoading()
            this.$am_toast.warning(msg)
          }
        })
        .catch((err) => {
          uni.hideLoading()
          this.$am_toast.error('查询失败，请稍后重试！')
        })
    },
    pageBack() {
      uni.navigateBack({
        delta: 1
      })
    },

    // 添加商品到购物车
    apiAddCart(data) {
      uni.showLoading({
        mask: true
      })
      apiAddCart(data)
        .then((res) => {
          let { state, msg } = res.data
          uni.hideLoading()
          if (state === 'OK') {
            this.$am_toast.success('成功添加购物车')
            uni.$emit(UPDATE_SHOPPING_CART)
            this.$store.dispatch('getCartNum')
            this.$store.dispatch('getNoticeData')
          } else {
            this.$am_toast(msg)
          }
        })
        .catch((err) => {
          uni.hideLoading()
          this.$am_toast.error('添加失败，请重新尝试！')
        })
    },
    goBuy() {
      if (!this.getDetailsSuccess) return
      if (this.goodsData.stock === 0) {
        this.$am_toast('暂无库存')
        return
      }
      this.$u.route('pages/place-order/submit-order', {
        ids: this.pageQuery.id
      })
    }
  }
}
</script>
<style lang="scss" scoped>
$page-plr: 16rpx;

.goods-banner {
  position: relative;
}

.goods-banner-swiper {
  width: 750rpx;
  height: 600rpx;
}

.short-nav-bar {
  position: fixed;
  z-index: 1500;
  left: 16rpx;
}

.page-back-btn {
  width: 50rpx;
}

.banner-item-img {
  width: 750rpx;
  height: 600rpx;
}

.goods-info {
  margin-top: 16rpx;
  padding: 20rpx 30rpx;
  background: #ffffff;
  border-radius: 16rpx;
}

.goods-price-box {
  font-weight: 500;
  font-size: 32rpx;
  color: #ec5d29;
  line-height: 44rpx;
}

.goods-price-num {
  font-weight: 600;
  font-size: 64rpx;
  color: #ec5d29;
  line-height: 64rpx;
}

.brand {
  height: 36rpx;
  line-height: 36rpx;
  font-size: 20rpx;
}

.brand-label {
  height: 36rpx;
  line-height: 36rpx;
  padding: 0 10rpx;
  background: #fef4ee;
  color: #f65300;
  border-radius: 0 4rpx 4rpx 0;
}

.brand-val {
  height: 36rpx;
  line-height: 36rpx;
  padding-left: 12rpx;
  padding-right: 4rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  background: linear-gradient(317deg, #fb8b02 0%, #f65301 100%);
  border-radius: 4rpx;
}

.goods-info-title {
  margin-top: 24rpx;
  font-weight: 600;
  font-size: 34rpx;
  color: #1d2129;
  line-height: 40rpx;
}

.goods-info-title-pd {
  padding-top: 24rpx;
  font-weight: 600;
  font-size: 34rpx;
  color: #1d2129;
  line-height: 40rpx;
  margin-bottom: 15rpx;
}

.goods-info-title-second {
  margin-top: 24rpx;
  font-weight: 600;
  font-size: 28rpx;
  color: #1d2129;
  line-height: 32rpx;
}

.goods-info-des {
  margin-top: 24rpx;
  font-size: 26rpx;
  font-weight: 400;
  color: #666666;
  line-height: 37rpx;
}

.goods-picture-wrap {
  margin-top: 16rpx;
  background-color: #fff;
  padding: 0 32rpx;
}

.goods-picture-list {
  width: 100%;
  border-radius: 16rpx;
}

.footer-bar {
  display: flex;
  justify-content: space-between;
  position: fixed;
  z-index: 1500;
  left: 0;
  bottom: 0;
  width: 750rpx;
  height: 174rpx;
  padding: 0 28rpx;
  background: #ffffff;
}

.footer-bar-wrap {
  display: flex;
  margin-top: 24rpx;
}

.footer-bar-place {
  height: 174rpx;
}

.join-cart-btn {
  margin-right: 30rpx;
}

.s-plain-btn {
  width: 231rpx;
  height: 80rpx;
  background: #fff;
  border-radius: 199rpx;
  border: 2rpx solid #ff4564;
  font-weight: 500;
  font-size: 30rpx;
  color: #f14141;
  line-height: 80rpx;
  text-align: center;
}

.s-primary-btn {
  text-align: center;
  font-size: 30rpx;
  font-weight: 500;
  color: #fff;
  width: 231rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(323deg, #ff4564 8%, #f14141 30%, #fc843b 100%);
  border-radius: 199rpx;
  border: none;
}

.footer-bar-button {
  &.disabled {
    opacity: 0.5;
  }
}

.martop {
  margin-top: 0rpx;
}

.flex {
  display: flex;
}

.label {
  max-width: 200rpx;
  min-width: 130rpx;
}

.item {
  color: #333333;
  flex: 1;
}

.flex-wrap {
  display: flex;
  flex-wrap: wrap;
}

.specStyle {
  margin-right: 15rpx;
  background: rgba(239, 239, 244, 0.5);
  color: #999999;
  border-radius: 4rpx;
  font-size: 22rpx;
  padding: 5rpx 10rpx;
  margin-bottom: 10rpx;
}

.clear-mt {
  margin-top: 0;
}

.popup-block {
  overflow: auto;
  padding: 40rpx 20rpx;
  margin-bottom: 80rpx;
}

.popup-block__title {
  margin-bottom: 50rpx;
  text-align: center;
}

.popup-block__item {
  margin: 20rpx;
}

.popup-block__item-title {
  margin-bottom: 10rpx;
  color: #333;
  font-size: 30rpx;
  font-weight: bold;
}

.freight-info-block {
  display: flex;
  width: 100%;
  height: 96rpx;
  padding: 10rpx 16rpx;
  margin-bottom: 10rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
}

.freight-info-block__left {
  min-width: 100rpx;
}

// .popup-wrap {
// 	position: relative;
// 	// height: 900rpx;
// }
// .close {
// 	position: absolute;
// 	bottom: 30rpx;
// 	left: 0;
// 	right: 0;
// 	width: 90%;
// 	height: 80rpx;
// 	line-height: 80rpx;
// 	margin: 30rpx auto 0;
// 	text-align: center;
// 	color: #fff;
// 	background: linear-gradient(132deg, #fe6507 0%, #f69027 100%);
// 	border-radius: 20px;
// }
.fs-20 {
  font-size: 34rpx;
}

.c-gray {
  color: #818592;
}

.mb-20 {
  margin-bottom: 20rpx;
}

.mr-10 {
  margin-right: 10rpx;
}
</style>
